<?php

namespace App\Containers\AppSection\User\UI\API\Requests;

use App\Containers\AppSection\Authorization\Tasks\GetAllRolesTask;
use App\Containers\AppSection\User\Traits\IsOwnerTrait;
use App\Ship\Exceptions\BadRequestException;
use App\Ship\Parents\Requests\Request;
use App\Ship\Rules\PhoneRule;
use Illuminate\Validation\Rule;

class UpdateUserRequest extends Request
{
    use IsOwnerTrait;

    /**
     * Define which Roles and/or Permissions has access to this request.
     */
    protected array $access = [
        'permissions' => 'update-users',
        'roles' => 'admin',
    ];

    /**
     * Id's that needs decoding before applying the validation rules.
     */
    protected array $decode = [
        'id',
    ];

    /**
     * Defining the URL parameters (`/stores/999/items`) allows applying
     * validation rules on them and allows accessing them like request data.
     */
    protected array $urlParameters = [
        'id',
    ];

    public function rules(): array
    {
        $roles = app(GetAllRolesTask::class)->withType('inner')->run();
        if (empty($roles)) {
            throw new BadRequestException();
        }

        return [
            'id' => 'required|exists:users,id',
            'email' => ['nullable', 'email', Rule::unique('users', 'email')],
            'phone' => ['nullable', new PhoneRule, Rule::unique('profiles', 'phone')],
            'fio' => ['nullable', 'max:100'],
            'roles' => ['array'],
            'roles.*' => [Rule::in($roles->pluck('name')->toArray())],
            'password' => ['nullable', 'min:8', 'max:255'],
            'other_information' => ['nullable', 'max:255'],
        ];
    }

    public function authorize(): bool
    {
        // is this an admin who has access to permission `update-users`
        // or the user is updating his own object (is the owner).

        return $this->check([
            'hasAccess|isOwner',
        ]);
    }
}
